﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace FillServiceForm
{
    class ClientSender
    {        
        private Thread clientSendThread = null;
        
        // still not has thread here
        public static String SendMessage(String str,String ip,int port)
        {
            //
            byte[] bytes = new byte[1024];
            try
            {
                //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                //IPAddress ipAddress = ipHostInfo.AddressList[0];
                IPAddress ipAddress = IPAddress.Parse(ip);
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
                Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                try
                {
                    sender.Connect(remoteEP);
                    Console.WriteLine("Socket connected to {0} ", sender.RemoteEndPoint.ToString());
                    byte[] msg = Encoding.ASCII.GetBytes(str);
                    int byteSent = sender.Send(msg);
                    int byteRec = sender.Receive(bytes);
                    //Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, byteRec));
                    //if(Encoding.ASCII.GetString(bytes, 0, byteRec)=="1")
                    System.Diagnostics.Debug.WriteLine(Encoding.ASCII.GetString(bytes, 0, byteRec));
                    Console.WriteLine(Encoding.ASCII.GetString(bytes, 0, byteRec));

                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                    return Encoding.ASCII.GetString(bytes, 0, byteRec);
                    //Console.Read();
                }
                catch (ArgumentNullException ane)
                {
                    Console.WriteLine("ArgumentNullException: {0}", ane.ToString());
                    return "-1";
                }
                catch (SocketException se)
                {                    
                    Console.WriteLine("SocketException: {0}", se.ToString());
                    return "-1";
                }
                catch (Exception e)
                {                    
                    Console.WriteLine("Unknown exception: {0}", e.ToString());
                    return "-1";
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e.ToString());
                return "-1";
            }
        }
    }
}
